<?php

namespace app\autologin\controller;

use think\Controller;
use think\Db;
use think\Cache;

use app\admin\model\SysconfigModel;

/**
 * 微信手机端登录
 * 1.采用WAP 引用JS方式,判断JS,如果不存在COOKIE，则跳转到用户解码页
 * 2. 用户解码页的URL，由后台指定，用于业务域名和 登录、支付域名分开，防封杀。
 */
class Wxlogin extends Controller
{
    public function _initialize()
    {
        $this->config_name= input("get.config_name");
        $this->data = $this->get_cache($this->config_name);
        $this->appid =  $this->data['appid'];
        $this->appsecret =  $this->data['appsecret'];
    }

    public function __construct()
    {
        Parent::__construct();
    }


    public function checkloginjsonp()
    {
       
     $ua = $_SERVER['HTTP_USER_AGENT']; 
        //MicroMessenger 是android/iphone版微信所带的
        //Windows Phone 是winphone版微信带的 (这个标识会误伤winphone普通浏览器的访问)
       
        if(strpos($ua, 'Firefox') == true){ 
         //echo "来自普通浏览器访问"; 
          return "";
        }
        $callback = $_GET['callback'];
        //JSONP
        $config_name=$this->config_name;
        $cookie=$_COOKIE;
        $useridname=$config_name.'_userid';
        $useridcheckname=$config_name.'_useridcheck';
       
        if (array_key_exists($useridname, $cookie)&&array_key_exists($useridcheckname, $cookie)) {
            $userid=$_COOKIE[$useridname];
            $usercheck=$_COOKIE[$useridcheckname];

            if ($this->md5Userid($userid, $config_name)== $usercheck) {
                $tablename= $this->data['tablename'];

                $member_wx_info = Db::name($tablename)->where("id", $userid)->find();

                cookie($config_name."_".'openid', $member_wx_info["openid"]);
                
 
 

                $a = array(
                'code'=>1,
                'msg' => "已登录",
                'useridname' => $useridname,
                'configname' => $config_name,
                'userid' =>$userid,
                'openid' =>$member_wx_info["openid"],
                'headimgurl'=>$member_wx_info["headimgurl"],
                'nickname'=>$member_wx_info["nickname"],
                
                'useridcheckname' => $useridcheckname,
                'usercheck' => $usercheck,
                'url' => ""
               );
			//	return json(['code' => 1,'openid' => $a['openid']]);
                $result = json_encode($a);
                echo $callback.'('.$result.')';
                exit;
            }
        }

    
        //refer
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $domain=$http_type.$_SERVER['HTTP_HOST'];
        if (array_key_exists('domain', $this->data)) {
            if (strpos("..". $this->data['domain'], "http")) {
                $domain= $this->data['domain'];
            }
        }


        //refer
        if (!array_key_exists('HTTP_REFERER', $_SERVER)) {
            $a = array(
                'code'=>-4,
                'msg' => "refer没有来源",
                'useridname' => "",
                'configname' => $config_name,
                'userid' =>"",
                'openid' =>"",
                'useridcheckname' =>"",
                'usercheck' => "",
                'url' => ""
               );
            $result = json_encode($a);
            echo $callback.'('.$result.')';
            exit;
        }
        $refer=$_SERVER["HTTP_REFERER"] ;
        cookie('refer', $refer, 300);

        $redirect_uri=urlencode($domain."/autologin/wxlogin/index/?config_name=".$this->config_name);

        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=". $this->appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
       
       
        $a = array(
            'code'=>2,
            'msg' => "未登录",
            'useridname' => "",
            'userid' =>"",
            'configname' => "",
            'useridcheckname' =>"",
            'openid' =>"",
            'usercheck' =>"",
            'url' => $url
           );
	 
        $result = json_encode($a);
        echo $callback.'('.$result.')';
        exit;
    }
    /**
     * 根据jmzhfs_sys_config中$config_name指定用户表及APPID，如此，则可以支持多公众号下登录
     * 使用 <script src="../checkLoginJs?config_name=wx"></script>
     * 如果未获取用户信息,则将会自动跳转,并插入用户数据，并返回到REFER页
     */
    public function checkloginjs()
    {
     
        //已登录还需要同步二个域名下的COOKIE，采用JS放头部。JQUERY请求用户数据的方式
        if ($this->isLogin($this->config_name)) {
            return $this->fetch();
        }


        //refer
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $domain=$http_type.$_SERVER['HTTP_HOST'];
        if (array_key_exists('domain', $this->data)) {
            if (strpos("..". $this->data['domain'], "http")) {
                $domain= $this->data['domain'];
            }
        }


        //refer
        if (!array_key_exists('HTTP_REFERER', $_SERVER)) {
            return json(['code'=>-4,'msg' =>"refer没有来源",'data' =>""]);
        }
        $refer=$_SERVER["HTTP_REFERER"] ;
        cookie('refer', $refer, 300);

        $redirect_uri=urlencode($domain."/autologin/wxlogin/index/?config_name=".$this->config_name);

        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=". $this->appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect";
        $this->assign([
            'msg' => "未登录",
            'useridname' => "",
            'userid' =>"",
            'configname' => "",
            'useridcheckname' =>"",
            'openid' =>"",
            'usercheck' =>"",
            'url' => $url
        ]);

        return $this->fetch();
    }

    public function index()
    {
        $code = request()->param('code');
        $data =  $this->getAccesstoken($code);

        $access_token = $data['access_token'];
        $openid = $data['openid'];
        $myuser= $this->checkUserInfo($openid);

        $refer=cookie('refer');
        if ($myuser!=null) {
            $this->setLogin($myuser["id"]);
            header("Location: ".$refer);
            return json(['code'=>200,'msg' =>$refer,'data' => $myuser  ]);
        }
        
        $info =  $this->getUserInfo($access_token, $openid);
        $info['from_type'] = "h5";
        $member_id = $this->insertUser($info);
        $this->setLogin($member_id);
        header("Location: ".$refer);
        return json(['code'=>100,'msg' =>"ok",'data' =>$info  ]);
    }


    /**
     * 注意OPENID和UNIONID区别
     */
    public function insertUser($arr=[])
    {
        $tablename= $this->data['tablename'];

        $member_wx_info = Db::name($tablename)->where("openid", $arr['openid'])->find();
        //判断用户是否注册
        if (!empty($member_wx_info)) {
            return $member_wx_info['id'];
        }

        $wx_param = [
            'nickname' => $arr['nickname'],
            'openid' =>  $arr['openid'],
            'headimgurl' => $arr['headimgurl'],
            'province' => $arr['province'],
            'country' =>  $arr['country'],
            'city' => $arr['city'],
            'sex' =>$arr['sex']
        ];
        $db = Db::name($tablename);
        $id = $db->insertGetId($wx_param);
        return $id;
    }

    private function getAccesstoken($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
        $ret = curlRequest($url);
        return json_decode($ret, true);
    }


    private function checkUserInfo($openid)
    {
        $tablename= $this->data['tablename'];
        $member_wx_info = Db::name($tablename)->where("openid", $openid)->find();
        if (!empty($member_wx_info)) {
            return $member_wx_info;
        }
        return null;
    }
    /**
     * 公众号获取用户信息
     */
    private function getUserInfo($access_token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
        $ret = curlRequest($url);
        return json_decode($ret, true);
    }

    public function md5Userid($userid, $config_name)
    {
        $configmodel = new SysconfigModel();
        $myconfig= $configmodel->getByName($config_name);
        if ($myconfig==null) {
            return "";
        }
        $data = json_decode($myconfig["value"], true);
        $str=$userid.$data['appid'].$data['salt'];
        $strmd5= md5($str);
        return $strmd5;
    }

    public function setLogin($userid)
    {
        $cookie=$_COOKIE;
        $useridname= $this->config_name.'_userid';
        $useridcheckname= $this->config_name.'_useridcheck';
        cookie($useridname, $userid, 3600);
        cookie($useridcheckname, $this->md5Userid($userid, $this->config_name), 3600);
    }

    public function isLogin($config_name)
    {
        $cookie=$_COOKIE;
        $useridname=$config_name.'_userid';
        $useridcheckname=$config_name.'_useridcheck';
       
        if (!array_key_exists($useridname, $cookie)) {
            return false;
        }
        if (!array_key_exists($useridcheckname, $cookie)) {
            return false;
        }

        $userid=$_COOKIE[$useridname];
        $usercheck=$_COOKIE[$useridcheckname];

        if ($this->md5Userid($userid, $config_name)== $usercheck) {
            $tablename= $this->data['tablename'];

            $member_wx_info = Db::name($tablename)->where("id", $userid)->find();

            if (empty($member_wx_info)) {
                return false; //数据库手动删除情况
            }
    
            cookie($config_name."_".'openid', $member_wx_info["openid"]);
            $this->assign([
                'msg' => "已登录",
                'useridname' => $useridname,
                'configname' => $config_name,
                'userid' =>$userid,
                'openid' =>$member_wx_info["openid"],
                'useridcheckname' => $useridcheckname,
                'usercheck' => $usercheck,
                'url' => ""
            ]);
            return true;
        }

        return false;
    }


    /**
     * 获取微信配置
     */
    private function get_cache($config_name)
    {
        $wxpay =  Cache::get("wx".$config_name);
        if (empty($wxpay)||true) {
            $configmodel = new SysconfigModel();
            $myconfig= $configmodel->getByName($config_name);
            if ($myconfig==null) {
                exit("请配置微信公众号登录".$config_name."未配置");
            }
            $wxpay = $myconfig["value"];

            Cache::set("wx".$config_name, $wxpay, 60);
        }
        return json_decode($wxpay, true);
    }
}
